package com.example.child_protection.service.impl;

import com.example.child_protection.dao.UserDao;
import com.example.child_protection.dto.base.BaseRequestDTO;
import com.example.child_protection.dto.info.UserInfoDTO;
import com.example.child_protection.dto.request.find.LoginRequestDTO;
import com.example.child_protection.dto.response.UserPageResponseDTO;
import com.example.child_protection.dto.response.UserResponseDTO;
import com.example.child_protection.enums.ResponseCodeEnums;
import com.example.child_protection.enums.ServiceActionEnums;
import com.example.child_protection.exception.MyBizException;
import com.example.child_protection.model.UserModel;
import com.example.child_protection.service.LoginService;
import com.example.child_protection.service.UserService;
import com.example.child_protection.service.base.MyBaseService;
import com.example.child_protection.service.base.MyServiceExecutor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * 登录service实现层
 * @date 2018-11-2
 * @author Biz
 */
@Component
public class LoginServiceImpl extends MyBaseService implements LoginService {

    @Autowired
    public UserDao userDao;

    /**
     * 登录接口
     * @param requestDTO
     * @return
     */
    @Override
    public UserResponseDTO login(LoginRequestDTO requestDTO){
        return this.service(ServiceActionEnums.LOGIN ,requestDTO, UserResponseDTO.class, new MyServiceExecutor<LoginRequestDTO, UserResponseDTO>() {
            @Override
            protected UserResponseDTO myprocess(LoginRequestDTO requestDTO) throws Exception {
                UserResponseDTO responseDTO = new UserResponseDTO();
                UserModel req = new UserModel();
                BeanUtils.copyProperties(requestDTO,req);
                int num = userDao.count(req);
                if(num==0){
                    throw new MyBizException("账号/密码错误");
                }
                if(num>1){
                    throw new MyBizException(ResponseCodeEnums.DATABASE_EXCEPTION.getDisplayName());
                }

                List<UserModel> result = userDao.findPage(req);
                UserInfoDTO user = new UserInfoDTO();
                BeanUtils.copyProperties(result.get(0),user);

                /**
                 * 修改上次登录时间
                 */
                req = new UserModel();
                req.setId(user.getId());
                req.setPreLoginTime(new Date());
                userDao.updatePreLoginTime(req);

                responseDTO.setInfo(user);
                responseDTO.successfully();
                return responseDTO;
            }
        });
    }

}
